package com.supreme.studyserver.aspect;

import com.supreme.commonboot.utils.AspectUtils;
import com.supreme.studyserver.annotation.SqlFilter;
import com.supreme.studyserver.utils.SqlUtils;
import org.apache.ibatis.session.SqlSessionFactory;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

@Aspect
@Configuration
public class SqlFilterAspect {

    @Resource
    private SqlSessionFactory sqlSessionFactory;

    /**
     * 切片
     */
    @Pointcut(value = "@within(com.supreme.studyserver.annotation.SqlFilter) || @annotation(com.supreme.studyserver.annotation.SqlFilter)")
    public void PointCut() {
    }

    @Before("PointCut()")
    public void beforeFilter(JoinPoint joinPoint) {
        Signature signature = joinPoint.getSignature();
        System.out.println("<==== SqlFilter Before signature: " + signature.toShortString());
    }

    @Around("PointCut()")
    public Object aroundFilter(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        SqlFilter sqlFilter = AspectUtils.findTypeOrMethodAnnotation(proceedingJoinPoint, SqlFilter.class);
        Boolean filterTestId = sqlFilter != null && sqlFilter.filterTest();

        System.out.println("<==== SqlFilter Around Before signature: " + proceedingJoinPoint.toShortString());
        String sql = SqlUtils.parseMybatisSql(proceedingJoinPoint, sqlSessionFactory, filterTestId);
        System.out.println("<==== SqlFilter Around sql: " + sql);
        Object proceed = proceedingJoinPoint.proceed();
        System.out.println("<==== SqlFilter Around After signature");
        return proceed;
    }
}
